package com.lwlk.zdk.controller.Down;

import com.lwlk.zdk.annotation.JwtIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping(value = "/down")
public class DownController {

    private static final Logger log = LoggerFactory.getLogger(DownController.class);

    @GetMapping("/JoinPlatform")
    @JwtIgnore
    public void getStaffTemplate(String type,HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String joinPlatformPath="接入平台.xlsx";
            String joinVehiclePath="接入车辆.xlsx";
            String vehiclePath="车辆.xlsx";
            String enterprisePath="业户管理.xlsx";
            String joinEnterprisePath="接入业户管理.xlsx";
            String name=type.equals("1")?joinPlatformPath:(type.equals("2")?joinVehiclePath:type.equals("3")?vehiclePath:type.equals("4")?enterprisePath:type.equals("5")?joinEnterprisePath:null);
            String excelName=name.replaceAll(".xlsx","");
            Resource resource = new DefaultResourceLoader().getResource("classpath:down/"+name);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(excelName.getBytes(), StandardCharsets.ISO_8859_1)
                    + ".xlsx");
            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            response.setContentType("");
            response.setHeader("", "");
            log.error("下载批量上传用户模板文件错误", e);
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                log.error("下载批量上传用户模板文件错误", e);
            }
        }
    }


}
